import src.snowboy.snowboydecoder as snowboydecoder
import os
import threading
from src.log import log
import threading

class Snowboy():
    def __init__(self, model, sensitivity=0.7, audio_gain=0.8):
        if not os.path.exists(model):
            raise ValueError("模型文件不存在: {}".format(model))
        if not (0 <= sensitivity <= 1):
            raise ValueError("灵敏度参数必须在 0 到 1 之间")
        if audio_gain < 0:
            raise ValueError("音频增益参数必须大于等于 0")

        self.model = model
        self.sensitivity = sensitivity
        self.audio_gain = audio_gain
        self.detector = snowboydecoder.HotwordDetector(
            self.model, sensitivity=self.sensitivity, audio_gain=self.audio_gain)
        self.interrupted = False
        self.log = log
        self.lock = threading.Lock()

    def set_detected_callback(self, callback):
        self.detected_callback = callback

    def start(self):
        if not hasattr(self, 'detected_callback'):
            raise ValueError("未设置 detected_callback")
        try:
            self.log.info("语音助手启动... 模型: {}, 灵敏度: {}, 音频增益: {}".format(
                self.model, self.sensitivity, self.audio_gain))
            # 在单独的线程执行检测
            threading.Thread(
                target=self.detector.start,
                args=(self.detected_callback, self._interrupt_callback),
                daemon=True
            ).start()
        except Exception as e:
            self.log.error("语音助手启动失败：{}".format(e))
            raise e

    def stop(self):
        try:
            with self.lock:
                self.interrupted = True
            self.log.info("语音助手停止")
        except Exception as e:
            self.log.error("语音助手停止失败：{}".format(e))

    def _close(self):
        try:
            self.detector.terminate()
            self.log.info("语音助手资源已释放")
        except Exception as e:
            self.log.error("语音助手资源释放失败：{}".format(e))

    def _interrupt_callback(self):
        with self.lock:
            return self.interrupted

    def __del__(self):
        self._close()